package com.hzw.net.extend

import android.content.Context
import android.net.Uri
import android.widget.ImageView
import cc.shinichi.library.ImagePreview
import cc.shinichi.library.bean.ImageInfo
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.hzw.net.R
import com.hzw.net.bean.Image

/**
 * 图片加载
 * 大图显示
 */
fun ImageView.load(
    url: String,
    isCircle: Boolean = false,
    skipMemoryCache: Boolean = false,
    placeResId: Int = R.drawable.ic_placeholder,
    fallbackResId: Int = R.drawable.ic_placeholder,
    errorResId: Int = R.drawable.ic_placeholder
) {
    val options = RequestOptions()
        .apply {
            error(errorResId)
            fallback(fallbackResId)
            placeholder(placeResId)
            skipMemoryCache(skipMemoryCache)
            diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
            if (isCircle) {
                circleCrop()
            }
        }
    Glide.with(this)
        .load(url)
        .apply(options)
        .into(this)
}

fun ImageView.load(
    url: Uri,
    placeResId: Int = R.drawable.ic_placeholder,
    fallbackResId: Int = R.drawable.ic_placeholder,
    errorResId: Int = R.drawable.ic_placeholder
) {
    val options = RequestOptions()
        .apply {
            error(errorResId)
            fallback(fallbackResId)
            placeholder(placeResId)
            centerCrop()
        }

    Glide.with(this)
        .load(url)
        .apply(options)
        .into(this)
}

fun List<String>.showImage(context: Context, position: Int = 0) {
    if (this.isNotEmpty()) {
        ImagePreview
            .getInstance()
            .setContext(context)
            .setIndex(position)
            .setEnableDragClose(true)
            .setErrorPlaceHolder(R.drawable.ic_placeholder)
            .setImageList(this)
            .setShowDownButton(true)
            .start()
    }
}

fun List<Image>.showImageByImage(context: Context, position: Int = 0) {
    val imageList = mutableListOf<ImageInfo>()
    forEach {
        imageList.add(ImageInfo().apply {
            originUrl = it.url
            thumbnailUrl = it.url
        })
    }
    ImagePreview
        .getInstance()
        .setContext(context)
        .setIndex(position)
        .setEnableDragClose(true)
        .setErrorPlaceHolder(R.drawable.ic_placeholder)
        .setImageInfoList(imageList)
        .setShowDownButton(true)
        .start()
}

fun String.showImage(context: Context) {
    ImagePreview
        .getInstance()
        .setContext(context)
        .setEnableDragClose(true)
        .setErrorPlaceHolder(R.drawable.ic_placeholder)
        .setImage(this)
        .setIndex(0)
        .setShowDownButton(true)
        .start()
}
